<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑早餐 - 晨食记</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#0A7CFF', // 鸿蒙蓝
                        morning: {
                            light: '#FFF3E0',
                            DEFAULT: '#FF9F43',
                            dark: '#F57C00'
                        },
                        health: {
                            light: '#E8F5E9',
                            DEFAULT: '#36D399',
                            warning: '#FFB400',
                            danger: '#F87272'
                        }
                    },
                    fontFamily: {
                        sans: ['HarmonyOS Sans', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .food-item-active {
                @apply bg-primary/10 border-primary text-primary;
            }
            .nutrition-bar {
                @apply h-2 rounded-full overflow-hidden;
            }
            .nutrition-fill {
                @apply h-full transition-all duration-1000 ease-out;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <button id="backBtn" class="text-gray-700 hover:text-primary transition-colors">
                <i class="fa fa-arrow-left"></i>
            </button>
            <h1 class="text-lg font-semibold text-gray-800">编辑今日早餐</h1>
            <button id="saveBtn" class="text-primary font-medium hover:text-primary/80 transition-colors">
                保存
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-20 pb-24">
        <!-- 日期显示 -->
        <div class="mt-6 text-center">
            <p class="text-gray-500" id="currentDate">2024年6月10日 星期一</p>
        </div>

        <!-- 已选早餐组合 -->
        <section class="mt-6 bg-white rounded-2xl p-5 shadow-sm">
            <h2 class="text-gray-800 font-medium mb-4">你的早餐组合</h2>
            
            <div id="selectedItems" class="flex flex-wrap gap-2 mb-4 min-h-[40px]">
                <!-- 已选食物标签会动态添加到这里 -->
                <div class="text-gray-500 text-sm italic">点击下方食物添加到你的早餐</div>
            </div>
            
            <!-- 营养均衡度 -->
            <div class="mt-4">
                <div class="flex justify-between text-sm mb-2">
                    <span class="text-gray-600">营养均衡度</span>
                    <span id="balanceScore" class="font-medium text-gray-800">0%</span>
                </div>
                <div class="nutrition-bar bg-gray-100">
                    <div id="balanceBar" class="nutrition-fill bg-health-danger" style="width: 0%"></div>
                </div>
            </div>
        </section>

        <!-- 食物分类选择 -->
        <section class="mt-6">
            <h2 class="text-gray-800 font-medium mb-4">选择食物</h2>
            
            <!-- 食物分类标签 -->
            <div class="flex overflow-x-auto scrollbar-hide gap-2 pb-2 mb-4">
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-primary text-white rounded-full text-sm" data-category="all">
                    全部
                </button>
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm text-gray-700 transition-colors" data-category="grain">
                    谷物主食
                </button>
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm text-gray-700 transition-colors" data-category="protein">
                    蛋白质
                </button>
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm text-gray-700 transition-colors" data-category="vegetable">
                    蔬菜水果
                </button>
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm text-gray-700 transition-colors" data-category="drink">
                    饮品
                </button>
                <button class="category-btn whitespace-nowrap px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-full text-sm text-gray-700 transition-colors" data-category="other">
                    其他
                </button>
            </div>
            
            <!-- 食物列表 -->
            <div class="grid grid-cols-3 gap-3">
                <!-- 谷物主食 -->
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="bread" data-category="grain" data-nutrition="carb">
                    <i class="fa fa-birthday-cake text-morning text-xl mb-1"></i>
                    <p class="text-xs">面包</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="porridge" data-category="grain" data-nutrition="carb">
                    <i class="fa fa-spoon text-morning text-xl mb-1"></i>
                    <p class="text-xs">粥</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="noodles" data-category="grain" data-nutrition="carb">
                    <i class="fa fa-cutlery text-morning text-xl mb-1"></i>
                    <p class="text-xs">面条</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="steamed" data-category="grain" data-nutrition="carb">
                    <i class="fa fa-circle-o text-morning text-xl mb-1"></i>
                    <p class="text-xs">包子/馒头</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="oatmeal" data-category="grain" data-nutrition="carb">
                    <i class="fa fa-square-o text-morning text-xl mb-1"></i>
                    <p class="text-xs">燕麦</p>
                </div>
                
                <!-- 蛋白质 -->
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="egg" data-category="protein" data-nutrition="protein">
                    <i class="fa fa-dot-circle-o text-health text-xl mb-1"></i>
                    <p class="text-xs">鸡蛋</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="milk" data-category="protein" data-nutrition="protein">
                    <i class="fa fa-glass text-health text-xl mb-1"></i>
                    <p class="text-xs">牛奶</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="yogurt" data-category="protein" data-nutrition="protein">
                    <i class="fa fa-flask text-health text-xl mb-1"></i>
                    <p class="text-xs">酸奶</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="tofu" data-category="protein" data-nutrition="protein">
                    <i class="fa fa-cube text-health text-xl mb-1"></i>
                    <p class="text-xs">豆腐</p>
                </div>
                
                <!-- 蔬菜水果 -->
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="apple" data-category="vegetable" data-nutrition="fiber">
                    <i class="fa fa-apple text-green-500 text-xl mb-1"></i>
                    <p class="text-xs">苹果</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="banana" data-category="vegetable" data-nutrition="fiber">
                    <i class="fa fa-star text-yellow-500 text-xl mb-1"></i>
                    <p class="text-xs">香蕉</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="tomato" data-category="vegetable" data-nutrition="fiber">
                    <i class="fa fa-circle text-red-500 text-xl mb-1"></i>
                    <p class="text-xs">番茄</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="salad" data-category="vegetable" data-nutrition="fiber">
                    <i class="fa fa-leaf text-green-400 text-xl mb-1"></i>
                    <p class="text-xs">沙拉</p>
                </div>
                
                <!-- 饮品 -->
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="coffee" data-category="drink" data-nutrition="other">
                    <i class="fa fa-coffee text-brown-500 text-xl mb-1"></i>
                    <p class="text-xs">咖啡</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="tea" data-category="drink" data-nutrition="other">
                    <i class="fa fa-leaf text-green-600 text-xl mb-1"></i>
                    <p class="text-xs">茶</p>
                </div>
                <div class="food-item bg-white rounded-xl p-3 shadow-sm text-center border border-gray-100 hover:border-primary/50 transition-all cursor-pointer" data-id="juice" data-category="drink" data-nutrition="other">
                    <i class="fa fa-glass text-orange-500 text-xl mb-1"></i>
                    <p class="text-xs">果汁</p>
                </div>
            </div>
        </section>

        <!-- 健康评估与建议 -->
        <section id="healthAssessment" class="mt-6 bg-white rounded-2xl p-5 shadow-sm hidden">
            <div id="healthyResult" class="hidden">
                <div class="flex items-start">
                    <div class="bg-health/10 p-2 rounded-full mr-3 mt-1">
                        <i class="fa fa-thumbs-up text-health"></i>
                    </div>
                    <div>
                        <h3 class="font-medium text-gray-800 mb-1">很棒的早餐组合！</h3>
                        <p class="text-gray-600 text-sm">你的早餐包含了均衡的营养成分，能为你提供充足的能量开启新的一天。</p>
                    </div>
                </div>
            </div>
            
            <div id="unhealthyResult" class="hidden">
                <div class="flex items-start">
                    <div class="bg-health-danger/10 p-2 rounded-full mr-3 mt-1">
                        <i class="fa fa-exclamation-triangle text-health-danger"></i>
                    </div>
                    <div>
                        <h3 class="font-medium text-gray-800 mb-1">可以优化的早餐组合</h3>
                        <p class="text-gray-600 text-sm mb-3" id="unhealthyReason">你的早餐缺少蛋白质来源，可能会导致上午能量不足。</p>
                        
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <h4 class="font-medium text-sm text-gray-800 mb-2">推荐组合</h4>
                            <p class="text-gray-600 text-sm" id="recommendation">当前选择 + 鸡蛋 + 牛奶</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div id="neutralResult" class="hidden">
                <div class="flex items-start">
                    <div class="bg-health-warning/10 p-2 rounded-full mr-3 mt-1">
                        <i class="fa fa-balance-scale text-health-warning"></i>
                    </div>
                    <div>
                        <h3 class="font-medium text-gray-800 mb-1">还不错的早餐</h3>
                        <p class="text-gray-600 text-sm mb-3">你的早餐基本满足需求，但稍作调整可以更健康。</p>
                        
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <h4 class="font-medium text-sm text-gray-800 mb-2">小建议</h4>
                            <p class="text-gray-600 text-sm" id="neutralSuggestion">可以添加一些水果来增加膳食纤维摄入。</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 保存成功弹窗 -->
    <div id="saveModal" class="fixed inset-0 bg-black/30 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl p-6 w-64 text-center transform transition-all duration-300 scale-90 opacity-0" id="modalContent">
            <div class="w-16 h-16 bg-health/20 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa fa-check text-2xl text-health"></i>
            </div>
            <h3 class="font-semibold text-lg mb-2">保存成功！</h3>
            <p class="text-gray-500 text-sm mb-4">已记录你的早餐组合</p>
            <button id="closeSaveModal" class="bg-primary text-white w-full py-2 rounded-lg hover:bg-primary/90 transition-colors">
                完成
            </button>
        </div>
    </div>

    <script>
        // 初始化日期
        const today = new Date();
        const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
        document.getElementById('currentDate').textContent = today.toLocaleDateString('zh-CN', dateOptions);
        
        // 已选食物存储
        const selectedFoods = new Set();
        const nutritionData = {
            carb: 0,       // 碳水化合物（谷物）
            protein: 0,    // 蛋白质
            fiber: 0,      // 膳食纤维（蔬果）
            other: 0       // 其他
        };
        
        // 食物DOM元素
        const foodItems = document.querySelectorAll('.food-item');
        const selectedItemsContainer = document.getElementById('selectedItems');
        const balanceScoreEl = document.getElementById('balanceScore');
        const balanceBarEl = document.getElementById('balanceBar');
        const healthAssessmentEl = document.getElementById('healthAssessment');
        
        // 食物点击事件 - 添加/移除食物
        foodItems.forEach(item => {
            item.addEventListener('click', () => {
                const foodId = item.getAttribute('data-id');
                const nutritionType = item.getAttribute('data-nutrition');
                
                if (selectedFoods.has(foodId)) {
                    // 移除食物
                    selectedFoods.delete(foodId);
                    item.classList.remove('food-item-active');
                    nutritionData[nutritionType]--;
                } else {
                    // 添加食物
                    selectedFoods.add(foodId);
                    item.classList.add('food-item-active');
                    nutritionData[nutritionType]++;
                }
                
                updateSelectedItems();
                calculateNutritionBalance();
                assessHealthiness();
            });
        });
        
        // 更新已选食物显示
        function updateSelectedItems() {
            // 清空容器
            selectedItemsContainer.innerHTML = '';
            
            if (selectedFoods.size === 0) {
                selectedItemsContainer.innerHTML = '<div class="text-gray-500 text-sm italic">点击下方食物添加到你的早餐</div>';
                healthAssessmentEl.classList.add('hidden');
                return;
            }
            
            // 添加已选食物标签
            selectedFoods.forEach(foodId => {
                const foodItem = document.querySelector(`.food-item[data-id="${foodId}"]`);
                const foodName = foodItem.querySelector('p').textContent;
                const foodIcon = foodItem.querySelector('i').outerHTML;
                
                const tag = document.createElement('div');
                tag.className = 'bg-primary/10 text-primary text-sm px-3 py-1 rounded-full flex items-center';
                tag.innerHTML = `${foodIcon} ${foodName} <button class="ml-1 text-primary/70 hover:text-primary/100" data-remove="${foodId}"><i class="fa fa-times-circle"></i></button>`;
                
                // 移除按钮事件
                tag.querySelector('button').addEventListener('click', (e) => {
                    e.stopPropagation();
                    const idToRemove = e.currentTarget.getAttribute('data-remove');
                    const nutritionType = document.querySelector(`.food-item[data-id="${idToRemove}"]`).getAttribute('data-nutrition');
                    
                    selectedFoods.delete(idToRemove);
                    document.querySelector(`.food-item[data-id="${idToRemove}"]`).classList.remove('food-item-active');
                    nutritionData[nutritionType]--;
                    
                    updateSelectedItems();
                    calculateNutritionBalance();
                    assessHealthiness();
                });
                
                selectedItemsContainer.appendChild(tag);
            });
            
            healthAssessmentEl.classList.remove('hidden');
        }
        
        // 计算营养均衡度
        function calculateNutritionBalance() {
            // 简单的营养均衡算法
            // 理想比例：碳水:蛋白质:纤维 = 3:2:1
            const hasCarb = nutritionData.carb > 0 ? 1 : 0;
            const hasProtein = nutritionData.protein > 0 ? 1 : 0;
            const hasFiber = nutritionData.fiber > 0 ? 1 : 0;
            
            // 基础分：是否包含三大类
            let baseScore = (hasCarb + hasProtein + hasFiber) * 30;
            
            // 比例分：根据比例调整
            let ratioScore = 0;
            if (hasCarb && hasProtein && hasFiber) {
                // 简单比例评估
                const total = nutritionData.carb + nutritionData.protein + nutritionData.fiber;
                const idealCarbRatio = nutritionData.carb / total;
                const idealProteinRatio = nutritionData.protein / total;
                const idealFiberRatio = nutritionData.fiber / total;
                
                // 理想比例接近0.5:0.3:0.2
                ratioScore = Math.max(0, 10 - 
                    (Math.abs(idealCarbRatio - 0.5) * 20 + 
                     Math.abs(idealProteinRatio - 0.3) * 20 + 
                     Math.abs(idealFiberRatio - 0.2) * 20));
            }
            
            const totalScore = Math.min(100, Math.round(baseScore + ratioScore));
            balanceScoreEl.textContent = `${totalScore}%`;
            
            // 更新进度条颜色和宽度
            balanceBarEl.style.width = `${totalScore}%`;
            if (totalScore >= 80) {
                balanceBarEl.className = 'nutrition-fill bg-health';
            } else if (totalScore >= 50) {
                balanceBarEl.className = 'nutrition-fill bg-health-warning';
            } else {
                balanceBarEl.className = 'nutrition-fill bg-health-danger';
            }
            
            return totalScore;
        }
        
        // 评估早餐健康度并给出建议
        function assessHealthiness() {
            // 隐藏所有结果
            document.getElementById('healthyResult').classList.add('hidden');
            document.getElementById('unhealthyResult').classList.add('hidden');
            document.getElementById('neutralResult').classList.add('hidden');
            
            const score = calculateNutritionBalance();
            
            // 基于营养数据给出评估
            if (score >= 80) {
                document.getElementById('healthyResult').classList.remove('hidden');
            } else if (score >= 50) {
                document.getElementById('neutralResult').classList.remove('hidden');
                
                // 根据缺失的营养给出建议
                let suggestion = '';
                if (nutritionData.fiber === 0) {
                    suggestion = '可以添加一些水果或蔬菜来增加膳食纤维摄入。';
                } else if (nutritionData.protein < 1) {
                    suggestion = '可以添加一个鸡蛋或一杯牛奶来增加蛋白质摄入。';
                } else if (nutritionData.carb < 1) {
                    suggestion = '可以添加一些谷物类食物，如面包或粥，提供足够能量。';
                } else {
                    suggestion = '整体不错，可以适当增加一些蔬菜或水果让营养更均衡。';
                }
                
                document.getElementById('neutralSuggestion').textContent = suggestion;
            } else {
                document.getElementById('unhealthyResult').classList.remove('hidden');
                
                // 分析原因
                let reason = '';
                let recommendation = '当前选择';
                
                if (nutritionData.carb === 0 && nutritionData.protein === 0 && nutritionData.fiber === 0) {
                    reason = '你的早餐组合不够均衡，缺少主要营养来源。';
                    recommendation = '推荐：面包 + 鸡蛋 + 苹果';
                } else if (nutritionData.carb === 0) {
                    reason = '你的早餐缺少谷物类主食，可能无法提供足够能量。';
                    recommendation += ' + 面包或粥';
                } else if (nutritionData.protein === 0) {
                    reason = '你的早餐缺少蛋白质来源，可能会导致上午能量不足。';
                    recommendation += ' + 鸡蛋或牛奶';
                } else if (nutritionData.fiber === 0) {
                    reason = '你的早餐缺少蔬菜水果，膳食纤维不足。';
                    recommendation += ' + 苹果或香蕉';
                } else {
                    reason = '你的早餐营养比例不够均衡，需要调整各类食物的比例。';
                    recommendation = '推荐：适量谷物 + 1-2种蛋白质食物 + 1种蔬菜水果';
                }
                
                document.getElementById('unhealthyReason').textContent = reason;
                document.getElementById('recommendation').textContent = recommendation;
            }
        }
        
        // 分类筛选
        const categoryBtns = document.querySelectorAll('.category-btn');
        categoryBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                // 更新按钮样式
                categoryBtns.forEach(b => {
                    b.classList.remove('bg-primary', 'text-white');
                    b.classList.add('bg-gray-100', 'text-gray-700');
                });
                btn.classList.remove('bg-gray-100', 'text-gray-700');
                btn.classList.add('bg-primary', 'text-white');
                
                // 筛选食物
                const category = btn.getAttribute('data-category');
                foodItems.forEach(item => {
                    if (category === 'all' || item.getAttribute('data-category') === category) {
                        item.style.display = 'block';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        });
        
        // 保存按钮事件
        const saveModal = document.getElementById('saveModal');
        const modalContent = document.getElementById('modalContent');
        
        document.getElementById('saveBtn').addEventListener('click', () => {
            if (selectedFoods.size === 0) {
                alert('请至少选择一种食物');
                return;
            }
            
            // 显示保存成功弹窗
            saveModal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-90', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 50);
            
            // 这里可以添加保存数据的逻辑
            console.log('保存的早餐组合:', Array.from(selectedFoods));
        });
        
        // 关闭保存弹窗
        document.getElementById('closeSaveModal').addEventListener('click', () => {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-90', 'opacity-0');
            setTimeout(() => {
                saveModal.classList.add('hidden');
                // 返回首页
                window.history.back();
            }, 300);
        });
        
        // 返回按钮
        document.getElementById('backBtn').addEventListener('click', () => {
            window.history.back();
        });
    </script>
</body>
</html>
